#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "config.h"


void main(){
    char * filepath = "./config.txt"; 

    int len = getFilelines(filepath);
    printf("文件有效行数:%d\n", len);

    if(!len){
        printf("配置文件没有内容");
    }

    struct ConfigInfo * info = NULL;
    //解析
    parseFile(filepath,len,&info);

    //测试根据key获取value
    
    printf("%s\n", getInfoByKey("heroAtk",info,len) );

    freeConfigInfo(info);
    info=NULL;
}



int getFilelines(char *filepath){

    FILE * file = fopen(filepath,"r");
    if(file==NULL){
        return -1;
    }

    char buf[1024] = {0};
    int line=0;
    while( fgets(buf,1024,file)!=NULL){
        
        if(isValidLine(buf)){
            line++;
            memset(buf,0,1024);
        }     
    }

    fclose(file);
    return line;
    
}

int isValidLine(char * str){
    // 查找字符串中是否有":"
    if (strchr(str,':') == NULL){
        return 0;  // 返回假 代表无效行
    }

    return 1;
}

void parseFile(char * filepath, int len, struct ConfigInfo ** configInfo){
    struct ConfigInfo * info = malloc(sizeof(struct ConfigInfo)*len);
    if(info ==NULL){
        return;
    }

    FILE * file = fopen(filepath,"r");
    if (file == NULL){
        return;
    }

    char buf[1024]= {0};
    int index=0;
    while( fgets(buf,1024,file)!=NULL){
        //判断是否是有效信息
        if(isValidLine(buf)){
            // 解析有效信息
            //1.清空key和value数组
            memset(info[index].key,0,64);
            memset(info[index].value,0,64);

            char * pos = strchr(buf,':');
            //key 赋值
            strncpy(info[index].key, buf, pos-buf);
            strncpy(info[index].value,pos+1,strlen(pos+1)-1);

            index++;

        }
        memset(buf,0,1024);
    }
    *configInfo = info;
}


// 获取值
char * getInfoByKey(char * key, struct ConfigInfo * configInfo,int len){
    for(int i=0;i<len;i++){
        if(strcmp(key,configInfo[i].key)==0){
            return configInfo[i].value;
        }
    }
    return NULL;
}


void  freeConfigInfo(struct ConfigInfo * ConfigInfo){
    if(ConfigInfo!=NULL){
        free(ConfigInfo);
        ConfigInfo = NULL;
    }
}

